package com.example.chat.config;

import com.example.chat.model.Permission;
import com.example.chat.model.Role;
import com.example.chat.model.RolePermission;
import com.example.chat.repository.PermissionRepository;
import com.example.chat.repository.RolePermissionRepository;
import com.example.chat.repository.RoleRepository;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.security.NullPermission;
import com.thoughtworks.xstream.security.PrimitiveTypePermission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StopWatch;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description
 * @Date 2022/11/17 10:55
 * @Author pq
 */
@Configuration
@Slf4j
public class InitData {

    @Resource
    private RoleRepository roleRepository;

    @Resource
    private PermissionRepository permissionRepository;

    @Resource
    private RolePermissionRepository rolePermissionRepository;

    @PostConstruct
    public void initRoleAndPermission() {
        StopWatch stopWatch=new StopWatch();

        stopWatch.start();
        log.info("初始化角色");
        InputStream roleInputStream = this.getClass().getClassLoader().getResourceAsStream("initData/role.xml");
        List<Role> roleList = (List<Role>) getXStream().fromXML(roleInputStream);
        roleRepository.saveAll(roleList);
        log.info("角色："+roleList);
        log.info("初始化角色结束");

        log.info("初始化权限");
        InputStream permissionInputStream = this.getClass().getClassLoader().getResourceAsStream("initData/permission.xml");
        List<Permission> permissions=(List<Permission>) getXStream().fromXML(permissionInputStream);
        permissionRepository.saveAll(permissions);
        log.info("权限："+permissions);
        log.info("初始化权限结束");

        log.info("初始化角色权限关联表");
        InputStream rolePermissionInputStream=this.getClass().getClassLoader().getResourceAsStream("initData/rolePermission.xml");
        List<RolePermission> rolePermissions=(List<RolePermission>)getXStream().fromXML(rolePermissionInputStream);
        rolePermissionRepository.saveAll(rolePermissions);
        log.info("角色权限关联表："+rolePermissions);
        log.info("初始化角色权限关联表结束");
        stopWatch.stop();
        log.info("初始化角色相关结束"+"用时："+stopWatch.getTotalTimeMillis()+"ms");
    }

    private XStream getXStream(){
        XStream xstream = new XStream();
        xstream.addPermission(NullPermission.NULL);
        xstream.addPermission(PrimitiveTypePermission.PRIMITIVES);
        xstream.allowTypeHierarchy(Collection.class);
        xstream.allowTypesByWildcard(new String[]{"com.example.chat.model.**"});
        return xstream;
    }
}
